package com.ruoyi.ldzlsb.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.ldzlsb.mapper.SbRepairOrderMapper;
import com.ruoyi.ldzlsb.domain.SbRepairOrder;
import com.ruoyi.ldzlsb.service.ISbRepairOrderService;
import com.ruoyi.ldzlsb.domain.SbRepairApplication;
import com.ruoyi.ldzlsb.service.ISbRepairApplicationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ruoyi.common.core.utils.SpringUtils;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.ldzlsb.service.ISbEquipmentService;

/**
 * 设备报修单Service业务层处理
 * 
 * @author anli
 * @date 2025-01-11
 */
@Service
public class SbRepairOrderServiceImpl implements ISbRepairOrderService 
{
    private static final Logger log = LoggerFactory.getLogger(SbRepairOrderServiceImpl.class);

    @Autowired
    private SbRepairOrderMapper sbRepairOrderMapper;

    /**
     * 查询设备报修单
     * 
     * @param repairId 设备报修单主键
     * @return 设备报修单
     */
    @Override
    public SbRepairOrder selectSbRepairOrderByRepairId(Long repairId)
    {
        return sbRepairOrderMapper.selectSbRepairOrderByRepairId(repairId);
    }

    /**
     * 查询设备报修单列表
     * 
     * @param sbRepairOrder 设备报修单
     * @return 设备报修单
     */
    @Override
    public List<SbRepairOrder> selectSbRepairOrderList(SbRepairOrder sbRepairOrder)
    {
        return sbRepairOrderMapper.selectSbRepairOrderList(sbRepairOrder);
    }

    /**
     * 新增设备报修单
     * 
     * @param sbRepairOrder 设备报修单
     * @return 结果
     */
    @Override
    public int insertSbRepairOrder(SbRepairOrder sbRepairOrder)
    {
        // 生成报修单号
        if (sbRepairOrder.getRepairCode() == null || sbRepairOrder.getRepairCode().isEmpty()) {
            sbRepairOrder.setRepairCode(generateRepairCode());
        }
        
        // 设置默认值
        if (sbRepairOrder.getStatus() == null || sbRepairOrder.getStatus().isEmpty()) {
            sbRepairOrder.setStatus("pending");
        }
        if (sbRepairOrder.getPriority() == null || sbRepairOrder.getPriority().isEmpty()) {
            sbRepairOrder.setPriority("normal");
        }
        if (sbRepairOrder.getReportTime() == null) {
            sbRepairOrder.setReportTime(DateUtils.getNowDate());
        }
        
        sbRepairOrder.setIsDelete("0");
        sbRepairOrder.setCreateBy(SecurityUtils.getUsername());
        sbRepairOrder.setCreateTime(DateUtils.getNowDate());
        return sbRepairOrderMapper.insertSbRepairOrder(sbRepairOrder);
    }

    /**
     * 修改设备报修单
     * 
     * @param sbRepairOrder 设备报修单
     * @return 结果
     */
    @Override
    public int updateSbRepairOrder(SbRepairOrder sbRepairOrder)
    {
        sbRepairOrder.setUpdateBy(SecurityUtils.getUsername());
        sbRepairOrder.setUpdateTime(DateUtils.getNowDate());
        return sbRepairOrderMapper.updateSbRepairOrder(sbRepairOrder);
    }

    /**
     * 批量删除设备报修单
     * 
     * @param repairIds 需要删除的设备报修单主键
     * @return 结果
     */
    @Override
    public int deleteSbRepairOrderByRepairIds(Long[] repairIds)
    {
        return sbRepairOrderMapper.deleteSbRepairOrderByRepairIds(repairIds);
    }

    /**
     * 删除设备报修单信息
     * 
     * @param repairId 设备报修单主键
     * @return 结果
     */
    @Override
    public int deleteSbRepairOrderByRepairId(Long repairId)
    {
        return sbRepairOrderMapper.deleteSbRepairOrderByRepairId(repairId);
    }

    /**
     * 根据报修单号查询设备报修单
     * 
     * @param repairCode 报修单号
     * @return 设备报修单
     */
    @Override
    public SbRepairOrder selectSbRepairOrderByRepairCode(String repairCode)
    {
        return sbRepairOrderMapper.selectSbRepairOrderByRepairCode(repairCode);
    }

    /**
     * 根据设备ID查询报修单列表
     * 
     * @param equipmentId 设备ID
     * @return 设备报修单集合
     */
    @Override
    public List<SbRepairOrder> selectSbRepairOrderByEquipmentId(Long equipmentId)
    {
        return sbRepairOrderMapper.selectSbRepairOrderByEquipmentId(equipmentId);
    }

    /**
     * 生成报修单号
     * 
     * @return 报修单号
     */
    @Override
    public String generateRepairCode()
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateStr = sdf.format(new Date());
        
        // 查询当天已有的报修单数量
        SbRepairOrder query = new SbRepairOrder();
        query.setReportTime(new Date());
        List<SbRepairOrder> orders = sbRepairOrderMapper.selectSbRepairOrderList(query);
        
        int count = orders.size() + 1;
        String countStr = String.format("%03d", count);
        
        return "BX" + dateStr + countStr;
    }

    /**
     * 处理报修单
     * 
     * @param sbRepairOrder 设备报修单
     * @return 结果
     */
    @Override
    public int handleSbRepairOrder(SbRepairOrder sbRepairOrder)
    {
        try {
            // 检查当前状态是否允许处理
            SbRepairOrder currentOrder = sbRepairOrderMapper.selectSbRepairOrderByRepairId(sbRepairOrder.getRepairId());
            if (currentOrder == null) {
                log.error("维修单不存在，ID: {}", sbRepairOrder.getRepairId());
                return 0;
            }
            
            if (!"processing".equals(currentOrder.getStatus())) {
                log.error("维修单状态不允许处理，当前状态: {}, ID: {}", currentOrder.getStatus(), sbRepairOrder.getRepairId());
                return 0;
            }
            
            sbRepairOrder.setStatus("repairing"); // 状态变更为维修中
        sbRepairOrder.setHandleTime(DateUtils.getNowDate());
        sbRepairOrder.setUpdateBy(SecurityUtils.getUsername());
        sbRepairOrder.setUpdateTime(DateUtils.getNowDate());
            
            int result = sbRepairOrderMapper.updateSbRepairOrder(sbRepairOrder);
            if (result > 0) {
                // 同步更新对应的报修单状态
                syncUpdateRepairApplication(currentOrder.getRemark());
                log.info("维修单状态更新成功，ID: {}, 新状态: repairing", sbRepairOrder.getRepairId());
            }
            return result;
        } catch (Exception e) {
            log.error("处理维修单失败，ID: {}", sbRepairOrder.getRepairId(), e);
            return 0;
        }
    }

    /**
     * 完成维修
     * 
     * @param sbRepairOrder 设备报修单
     * @return 结果
     */
    @Override
    public int completeSbRepairOrder(SbRepairOrder sbRepairOrder)
    {
        try {
            // 检查当前状态是否允许完成
            SbRepairOrder currentOrder = sbRepairOrderMapper.selectSbRepairOrderByRepairId(sbRepairOrder.getRepairId());
            if (currentOrder == null) {
                log.error("维修单不存在，ID: {}", sbRepairOrder.getRepairId());
                return 0;
            }
            
            log.info("当前维修单状态: {}, ID: {}", currentOrder.getStatus(), sbRepairOrder.getRepairId());
            
            // 允许从pending、processing或repairing状态完成维修
            if (!"pending".equals(currentOrder.getStatus()) && 
                !"processing".equals(currentOrder.getStatus()) && 
                !"repairing".equals(currentOrder.getStatus())) {
                log.error("维修单状态不允许完成，当前状态: {}, ID: {}", currentOrder.getStatus(), sbRepairOrder.getRepairId());
                return 0;
            }
            
            sbRepairOrder.setStatus("completed");
            sbRepairOrder.setCloseTime(DateUtils.getNowDate());
            sbRepairOrder.setUpdateBy(SecurityUtils.getUsername());
            sbRepairOrder.setUpdateTime(DateUtils.getNowDate());
            
            int result = sbRepairOrderMapper.updateSbRepairOrder(sbRepairOrder);
            log.info("更新维修单结果: {}, ID: {}", result, sbRepairOrder.getRepairId());
            
            if (result > 0) {
                // 自动更新设备状态为空闲
                updateEquipmentStatusToIdle(currentOrder.getEquipmentId());
                
                // 同步更新对应的报修单状态
                syncUpdateRepairApplication(currentOrder.getRemark());
                log.info("维修单完成成功，ID: {}, 状态: completed", sbRepairOrder.getRepairId());
            }
            return result;
        } catch (Exception e) {
            log.error("完成维修单失败，ID: {}", sbRepairOrder.getRepairId(), e);
            return 0;
        }
    }

    /**
     * 更新设备状态为空闲
     * 
     * @param equipmentId 设备ID
     */
    private void updateEquipmentStatusToIdle(Long equipmentId) {
        try {
            // 调用设备Service
            ISbEquipmentService equipmentService = SpringUtils.getBean(ISbEquipmentService.class);
            if (equipmentService != null) {
                int updateResult = equipmentService.updateStatus(equipmentId, "0", "维修完成，设备恢复正常");
                if (updateResult > 0) {
                    log.info("设备状态更新为空闲成功，设备ID: {}", equipmentId);
                } else {
                    log.error("设备状态更新为空闲失败，设备ID: {}", equipmentId);
                }
            } else {
                log.error("获取设备服务失败");
            }
        } catch (Exception e) {
            log.error("更新设备状态为空闲失败，设备ID: {}", equipmentId, e);
        }
    }

    /**
     * 取消维修单
     * 
     * @param repairId 维修单ID
     * @param reason 取消原因
     * @return 结果
     */
    @Override
    public int cancelSbRepairOrder(Long repairId, String reason)
    {
        try {
            // 检查当前状态是否允许取消
            SbRepairOrder currentOrder = sbRepairOrderMapper.selectSbRepairOrderByRepairId(repairId);
            if (currentOrder == null) {
                log.error("维修单不存在，ID: {}", repairId);
                return 0;
            }
            
            if ("completed".equals(currentOrder.getStatus()) || "canceled".equals(currentOrder.getStatus())) {
                log.error("维修单状态不允许取消，当前状态: {}, ID: {}", currentOrder.getStatus(), repairId);
                return 0;
            }
            
            SbRepairOrder updateOrder = new SbRepairOrder();
            updateOrder.setRepairId(repairId);
            updateOrder.setStatus("canceled");
            updateOrder.setRemark(reason);
            updateOrder.setUpdateBy(SecurityUtils.getUsername());
            updateOrder.setUpdateTime(DateUtils.getNowDate());
            
            int result = sbRepairOrderMapper.updateSbRepairOrder(updateOrder);
            if (result > 0) {
                // 同步更新对应的报修单状态
                syncUpdateRepairApplication(currentOrder.getRemark());
                log.info("取消维修单成功，ID: {}, 原因: {}", repairId, reason);
            }
            return result;
        } catch (Exception e) {
            log.error("取消维修单失败，ID: {}", repairId, e);
            return 0;
        }
    }

    /**
     * 同步更新对应的报修单状态
     * 
     * @param remark 维修单备注（包含报修单编号）
     */
    private void syncUpdateRepairApplication(String remark) {
        try {
            if (remark != null && remark.contains("由报修单自动生成：")) {
                String repairCode = remark.substring(remark.indexOf("：") + 1);
                
                // 调用报修单Service
                ISbRepairApplicationService repairApplicationService = SpringUtils.getBean(ISbRepairApplicationService.class);
                if (repairApplicationService != null) {
                    // 查询对应的报修单
                    SbRepairApplication query = new SbRepairApplication();
                    query.setRepairCode(repairCode);
                    List<SbRepairApplication> applications = repairApplicationService.findRepairApplication(query);
                    
                    if (!applications.isEmpty()) {
                        SbRepairApplication application = applications.get(0);
                        // 根据维修单状态同步报修单状态
                        SbRepairOrder currentOrder = sbRepairOrderMapper.selectSbRepairOrderByRepairCode(repairCode);
                        if (currentOrder != null) {
                            application.setStatus(currentOrder.getStatus());
                            application.setUpdateBy(SecurityUtils.getUsername());
                            application.setUpdateTime(DateUtils.getNowDate());
                            repairApplicationService.updateRepairApplication(application);
                            log.info("同步更新报修单状态成功，报修单编号: {}, 状态: {}", repairCode, currentOrder.getStatus());
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("同步更新报修单状态失败，备注: {}", remark, e);
        }
    }

    /**
     * 关闭报修单
     * 
     * @param repairId 报修单ID
     * @return 结果
     */
    @Override
    public int closeSbRepairOrder(Long repairId)
    {
        SbRepairOrder sbRepairOrder = new SbRepairOrder();
        sbRepairOrder.setRepairId(repairId);
        sbRepairOrder.setStatus("closed");
        sbRepairOrder.setCloseTime(DateUtils.getNowDate());
        sbRepairOrder.setUpdateBy(SecurityUtils.getUsername());
        sbRepairOrder.setUpdateTime(DateUtils.getNowDate());
        return sbRepairOrderMapper.updateSbRepairOrder(sbRepairOrder);
    }

    /**
     * 根据报修单来源查询维修单
     * 
     * @param sourceCode 报修单编号
     * @return 设备维修单
     */
    @Override
    public SbRepairOrder selectSbRepairOrderBySourceCode(String sourceCode) {
        // 查找remark字段中包含sourceCode的维修单
        SbRepairOrder query = new SbRepairOrder();
        query.setRemark("由报修单自动生成：" + sourceCode);
        List<SbRepairOrder> orders = sbRepairOrderMapper.selectSbRepairOrderList(query);
        
        // 如果找到则返回第一个匹配的记录
        if (orders != null && !orders.isEmpty()) {
            return orders.get(0);
        }
        
        return null;
    }
} 